import React, { useState, useEffect } from 'react';
import { Eye, Share2, Download, MoreVertical, FileText, Image as ImageIcon } from 'lucide-react';
import FileIcon from './FileIcon';
import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Trash2 } from 'lucide-react';

const FilePreviewGrid = ({ files, selectedFiles, onFileSelect, onFolderOpen, onPreviewFile, onDownload, onDelete }) => {
  // 判断文件是否为图片类型
  const isImageFile = (file) => {
    return file.type === 'image' || ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].some(ext => 
      file.name.toLowerCase().endsWith(`.${ext}`)
    );
  };

  // 获取图片预览URL（使用 downloadUrl/fileUrl 字段，带token）
  const getImagePreviewUrl = (file) => {
    // 使用 fileUrl 字段（对应后端的 downloadUrl）
    const baseUrl = file.fileUrl;
    if (!baseUrl) return null;
    
    const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
    if (!token) return baseUrl;
    
    const separator = baseUrl.includes('?') ? '&' : '?';
    return `${baseUrl}${separator}accessToken=${token}`;
  };

  // 图片加载状态管理
  const [imageLoadStates, setImageLoadStates] = useState({});

  const handleImageLoad = (fileId) => {
    setImageLoadStates(prev => ({ ...prev, [fileId]: 'loaded' }));
  };

  const handleImageError = (fileId) => {
    setImageLoadStates(prev => ({ ...prev, [fileId]: 'error' }));
  };

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
      {files.map((file) => {
        const isImage = isImageFile(file);
        const previewUrl = isImage ? getImagePreviewUrl(file) : null;
        const imageLoadState = imageLoadStates[file.id];

        return (
          <div
            key={file.id}
            className={`file-grid-item group relative ${
              selectedFiles.includes(file.id) ? 'ring-2 ring-primary bg-primary/5' : ''
            }`}
            onClick={() => onFileSelect(file.id)}
            onDoubleClick={() => file.isDirectory && onFolderOpen(file)}
          >
            {/* 选择框 */}
            <div className="absolute top-2 left-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity">
              <input
                type="checkbox"
                checked={selectedFiles.includes(file.id)}
                onChange={(e) => {
                  e.stopPropagation();
                  onFileSelect(file.id, e);
                }}
                onClick={(e) => e.stopPropagation()}
                className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50 cursor-pointer"
              />
            </div>

            {/* 预览内容区域 */}
            <div className="flex flex-col items-center text-center pt-2">
              {/* 图片预览或文件图标 */}
              <div className="w-full aspect-square mb-2 rounded-lg overflow-hidden bg-material-grey-100 flex items-center justify-center">
                {isImage && previewUrl ? (
                  <div className="relative w-full h-full">
                    {imageLoadState !== 'loaded' && imageLoadState !== 'error' && (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
                      </div>
                    )}
                    {imageLoadState !== 'error' && (
                      <img
                        src={previewUrl}
                        alt={file.name}
                        className={`w-full h-full object-cover transition-opacity duration-300 ${
                          imageLoadState === 'loaded' ? 'opacity-100' : 'opacity-0'
                        }`}
                        onLoad={() => handleImageLoad(file.id)}
                        onError={() => handleImageError(file.id)}
                      />
                    )}
                    {imageLoadState === 'error' && (
                      <div className="w-full h-full flex items-center justify-center">
                        <div className="text-center">
                          <ImageIcon className="w-12 h-12 text-material-grey-400 mx-auto mb-2" />
                          <p className="text-xs text-material-grey-500">预览失败</p>
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="flex items-center justify-center">
                    <FileIcon type={file.type} size="large" />
                  </div>
                )}
              </div>

              {/* 文件信息 */}
              <div className="w-full px-2">
                <p className="text-sm font-medium text-material-grey-800 truncate mb-1">
                  {file.name}
                </p>
                
                <div className="text-xs text-material-grey-500">
                  {file.isDirectory ? (
                    <span>{file.items || 0} 个项目</span>
                  ) : (
                    <span>{file.size}</span>
                  )}
                </div>
                
                <div className="text-xs text-material-grey-400 mt-1">
                  {file.modified}
                </div>
              </div>
            </div>

            {/* 操作按钮 - 悬停时显示 */}
            <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/40 rounded-lg z-10">
              <div className="grid grid-cols-2 gap-2">
                {!file.isDirectory && (
                  <Button
                    size="lg"
                    variant="secondary"
                    className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                    onClick={(e) => {
                      e.stopPropagation();
                      onPreviewFile && onPreviewFile(file);
                    }}
                    title="预览文件"
                  >
                    <Eye className="w-5 h-5" />
                  </Button>
                )}
                
                {!file.isDirectory && (
                  <Button
                    size="lg"
                    variant="secondary"
                    className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                    onClick={(e) => {
                      e.stopPropagation();
                      onDownload && onDownload(file, e);
                    }}
                    title="下载文件"
                  >
                    <Download className="w-5 h-5" />
                  </Button>
                )}
                
                <Button
                  size="lg"
                  variant="secondary"
                  className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                  title="分享文件"
                >
                  <Share2 className="w-5 h-5" />
                </Button>
                
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      size="lg"
                      variant="secondary"
                      className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                      onClick={(e) => e.stopPropagation()}
                      title="更多操作"
                    >
                      <MoreVertical className="w-5 h-5" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem
                      onClick={(e) => {
                        e.stopPropagation();
                        onDelete && onDelete(file, e);
                      }}
                      className="text-red-600 focus:text-red-600"
                    >
                      <Trash2 className="w-4 h-4 mr-2" />
                      删除
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>

            {/* 悬停效果 */}
            <div className="absolute inset-0 bg-primary/5 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg pointer-events-none" />
          </div>
        );
      })}
    </div>
  );
};

export default FilePreviewGrid;
